package org.hq.video;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.hq.video.utils.JwtTokenUtil;
import org.hq.video.service.TokenService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@SpringBootTest
class JwtTokenUtilTest {
    //加密密钥
    private static final String SECRET_KEY = "DFabcd8efg5ab4cdef1ghijklmno9pq4r5s3t2uv1w0xyz"; // 密钥
    //加密方式
    private static final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    @Autowired
    private TokenService tu;

    @Test
    void checkToken() {
    //tu.saveToken("qq",120);


    }

    //验证token如果正确返回用户id
    @Test
    void createToken() {
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJyb290IiwiaWF0IjoxNzI1ODI4NzYwLCJleHAiOjE3MjU4Mjg3NjB9.3oOsoA3KdkQ_QopPb5MffonXnA-w5V-hu8RkiFhpGlA";
        try {
            // 解析token
            JwtParser jwt = Jwts.parser();
            // 设置密钥
            jwt.setSigningKey(Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8)));
            // 解析token
            Claims claims = jwt.parseClaimsJws(token).getBody();
            Date expiration = claims.getExpiration(); // 获取过期时间
            // 验证token是否过期
            if (expiration.before(new Date())) {
                System.out.println("token是否过期");
                return;
            }


            // 验证负载中的信息
            String subject = claims.getSubject(); // 获取用户ID或其他信息
            System.out.println("用户id = " + subject);
        } catch (ExpiredJwtException e) {

        }
    }


    @Test
    void createTokens() {


        String tokey = JwtTokenUtil.createToken("GHJ", System.currentTimeMillis() + 60 * 60 * 1000L * 3);
        System.out.println(tokey);
        // R r = checkToken(tokey);

        //System.out.println( r.toString());
    }


}